package com.ic.controller;

import com.ic.base.BaseController;
import com.ic.base.OperatorType;
import com.ic.base.PageInfo;
import com.ic.entity.ItemType;
import com.ic.entity.PicInfo;
import com.ic.service.ItemTypeService;
import com.ic.util.FileUploadUtil;
import com.ic.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 物品类型控制层类
 * Author: spark
 * Date  : 2017/6/30
 * Time  : 11:00.
 */
@Controller
@RequestMapping("/itemTypeController")
public class ItemTypeController extends BaseController {
	@Resource
	private ItemTypeService itemTypeService;

	/**
	 * 根据查询条件获取物品类型信息
	 *
	 * @param itemType 物品类型信息
	 * @param pageInfo 分页信息
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/showItemTypeList")
	@ResponseBody
	public Map showItemTypeList(ItemType itemType, PageInfo pageInfo) {
		return success(itemTypeService.showItemTypeList(itemType, pageInfo), OperatorType.SELECT, null);
	}

	/**
	 * 根据状态查询物品类型信息
	 *
	 * @param state 物品类型状态
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/selectSubject")
	@ResponseBody
	public Map selectSubject(String state) {
		return success(itemTypeService.selectSubject(state), OperatorType.SELECT, null);
	}

	/**
	 * 处理文件上传
	 *
	 * @param file    上传的文件信息
	 * @param request request请求
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/fileUpload")
	public Map upload(@RequestParam("txt_add_pic") MultipartFile file, HttpServletRequest request) {
		Map map = new HashMap<>();
		String filePath = request.getServletContext().getRealPath("/");
		String fileNewName = FileUploadUtil.getFileNewName(file);
		String uploadPath = "upload/" + fileNewName;
		filePath += uploadPath;
		try {
			//将文件输出到指定目录
			file.transferTo(new File(filePath));
		} catch (IOException e) {
			LOGGER.warn("文件上传失败！！！", e);
		}
		map.put("filePath", fileNewName);
		return success(map, OperatorType.UPLOAD, null);
	}

	/**
	 * 检查货号是否已存在
	 *
	 * @param itemNum 货号
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/checkItemNum")
	public Map checkItemNum(String itemNum) {
		return success(itemTypeService.checkItemNum(itemNum), OperatorType.SELECT, null);
	}

	/**
	 * 添加物品类型信息
	 *
	 * @param itemType 物品类型信息
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addItemType")
	@ResponseBody
	public Map addItemType(/*@RequestParam("file")*/ MultipartFile file, HttpServletRequest request, ItemType itemType, String fileSize) throws IOException, ServletException {
		Map map = new HashMap();
		PicInfo picInfo = null;
		if (file != null) {
			String filePath = request.getServletContext().getRealPath("/");
			String fileNewName = FileUploadUtil.getFileNewName(file);
			String uploadPath = "upload" + File.separator + fileNewName;
			filePath += uploadPath;
			try {
				//将文件输出到指定目录
				file.transferTo(new File(filePath));
			} catch (IOException e) {
				LOGGER.warn("文件上传失败！！！", e);
				return failed(map, OperatorType.UPLOAD, "文件上传失败！");
			}
			picInfo = new PicInfo();
			picInfo.setPicName(file.getOriginalFilename());
			picInfo.setPicAlias(fileNewName);
			picInfo.setPicSize(fileSize);
			picInfo.setUrl(uploadPath);
			//编号，如果只有一张图片就设置为1，有多张这个值依次递增
			picInfo.setNum("1");
		}


		itemTypeService.addItemType(itemType, picInfo);
		return success(map, OperatorType.ADD, null);
	}

	/**
	 * 根据物品类型ID查询物品类型信息
	 *
	 * @param id 品名ID
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/showItemType")
	@ResponseBody
	public Map showItemType(String id) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String requestURL = request.getRequestURL().toString();
		requestURL = StringUtil.subStringStr(requestURL);
		Map map = itemTypeService.showItemType(id);
		map.put("requestURL", requestURL);
		return success(map, OperatorType.SELECT, null);
	}

	/**
	 * 根据ID更新物品类型信息
	 *
	 * @param itemType 物品类型信息
	 * @return 返回Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/updateItemType")
	@ResponseBody
	public Map updateItemType(/*@RequestParam("file")*/ MultipartFile file, HttpServletRequest request,
							  ItemType itemType, String fileSize, String picId, String sourcePicName, String uploadTag) {
		Map map = new HashMap();
		PicInfo picInfo = null;
		// 处理文件上传。由于页面有一个图片显示，如果不判断文件上传标志，将会把显示的文件再次上传，
		// 因此除了要判断file是否为空外，还要根据上传标志进行再次判断
		if (file != null && StringUtil.notNullAndNotBlank(uploadTag)) {
			String filePath = request.getServletContext().getRealPath("/");
			String absolutePath = request.getServletContext().getRealPath("/upload");
			String fileNewName = FileUploadUtil.getFileNewName(file);
			String uploadPath = "upload" + File.separator + fileNewName;
			filePath += uploadPath;
			try {
				//将文件输出到指定目录
				file.transferTo(new File(filePath));
				//删除原来的文件，先判断之前是否有文件
				if (StringUtil.notNullAndNotBlank(sourcePicName)) {
					File existFile = new File(absolutePath, sourcePicName);
					// 判断要删除的文件是否存在
					if (existFile.exists()) {
						Files.delete(Paths.get(absolutePath, sourcePicName));
					}
				}

			} catch (IOException e) {
				LOGGER.warn("文件上传失败！！！", e);
				return failed(map, OperatorType.UPLOAD, "文件上传失败！");
			}
			picInfo = new PicInfo();

			picInfo.setId(picId);
			picInfo.setPicName(file.getOriginalFilename());
			picInfo.setPicAlias(fileNewName);
			picInfo.setPicSize(fileSize);
			picInfo.setUrl(uploadPath);
			//编号，如果只有一张图片就设置为1，有多张这个值依次递增
			picInfo.setNum("1");
		}
		itemTypeService.updateByPrimaryKeySelective(itemType, picInfo);
		return success(new HashMap<>(), OperatorType.UPDATE, null);
	}

}
